﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Paras2Excel
{
    class Program
    {
        private static string CleanHeader(string rawHeader)
        {
            return Regex.Replace(rawHeader, @"[\d\.。、\s]", "");
        }

        private static void WriteExcel(List<Tuple<string, string>> lst, string outFile)
        {

            using (var package = new ExcelPackage())
            {
                var sheet = package.Workbook.Worksheets.Add("Sheet1");
                int rowIndex = 0;

                foreach (Tuple<string, string> tu in lst)
                {
                    rowIndex++;
                    sheet.Cells[rowIndex, 1].Value = CleanHeader(tu.Item1);

                    sheet.Cells[rowIndex, 2].Value = tu.Item2;
                }
                sheet.Cells.AutoFitColumns(0);
                string excelFileName = Path.Combine(outFile);
                package.SaveAs(new FileInfo(excelFileName));
                Console.WriteLine(excelFileName);
            }
        }
        private static void ConvertOneFile(string txtFileName)
        {
            Console.WriteLine(txtFileName);
            string content = File.ReadAllText(txtFileName, Encoding.UTF8);
            Regex reg = new Regex(@"(^\s*\d+.+?\S+)", RegexOptions.Compiled | RegexOptions.Multiline);
            List<Tuple<string, string>> lst = new List<Tuple<string, string>>();
            string head = null;
            foreach (var s in reg.Split(content))
            {
                if (reg.IsMatch(s))
                    head = s;
                else if (head != null)
                {
                    Console.WriteLine(head.Trim());
                    lst.Add(new Tuple<string, string>(head, s));
                }
            }
            WriteExcel(lst, txtFileName + ".xlsx");

        }
        static void Main(string[] args)
        {
            //if (DateTime.Now < new DateTime(2021, 9, 1) ||
            //  DateTime.Now > new DateTime(2021, 9, 3))
            //{
            //    Environment.Exit(0);
            //}
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            DirectoryInfo di = new DirectoryInfo("txt");
            if (!di.Exists)
            {
                di.Create();
            }
            Console.WriteLine("正在搜索txt/下的txt文件...");
            foreach (FileInfo txtFile in di.GetFiles("*.txt"))
            {
                try
                {
                    ConvertOneFile(txtFile.FullName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.WriteLine("结束！");
            Console.ReadKey();
        }
    }
}
